package bma.common.langutil.io;

import java.net.InetSocketAddress;
import java.net.SocketAddress;

import bma.common.langutil.core.StringUtil;
import bma.common.langutil.core.ValueUtil;

/**
 * 主机端口
 * 
 * @author guanzhong
 * @since 1.0 (imported from BMA.ESP Project)
 * 
 */
public class HostPort {

	protected String host;
	protected int port;

	public HostPort() {
		super();
	}

	public HostPort(String host, int port) {
		super();
		this.host = host;
		this.port = port;
	}

	public HostPort(String host) {
		super();
		this.host = host;
	}

	public HostPort(int port) {
		super();
		this.port = port;
	}

	public String getHost() {
		return host;
	}

	public void setHost(String host) {
		this.host = host;
	}

	public boolean hasPort() {
		return port > 0;
	}

	public int getPort() {
		return port;
	}

	public int getPort(int def) {
		if (!hasPort())
			return def;
		return port;
	}

	public void setPort(int port) {
		this.port = port;
	}
	
	public static HostPort fromHostString(String v, int defaultPort) {
		HostPort r = new HostPort();
		r.setHostString(v, defaultPort);
		return r;
	}

	public void setHostString(String v, int defaultPort) {
		if (ValueUtil.empty(v))
			throw new NullPointerException("hoststring");
		String[] slist = v.split(":");
		if (slist.length > 1) {
			setHost(slist[0]);
			setPort(ValueUtil.intValue(slist[1], defaultPort));
		} else {
			setHost(slist[0]);
			setPort(defaultPort);
		}
	}

	@Override
	public boolean equals(Object obj) {
		if (super.equals(obj))
			return true;
		if (obj instanceof HostPort) {
			HostPort o = (HostPort) obj;
			if (o.port != port)
				return false;
			return StringUtil.equals(host, o.host);
		}
		return false;
	}

	@Override
	public int hashCode() {
		int p1 = host == null ? 0 : host.hashCode();
		return p1 * 37 + port;
	}

	public static boolean isAll(String host) {
		if (ValueUtil.empty(host))
			return true;
		if ("*".equals(host))
			return true;
		return false;
	}

	public SocketAddress createInetSocketAddress() {
		if (isAll(this.host)) {
			return new InetSocketAddress(getPort());
		} else {
			return new InetSocketAddress(this.host, getPort());
		}
	}

	public static HostPort createFrom(SocketAddress addr) {
		HostPort hp = new HostPort();
		if (addr instanceof InetSocketAddress) {
			InetSocketAddress inet = (InetSocketAddress) addr;
			hp.setHost(inet.getAddress().getHostAddress());
			hp.setPort(inet.getPort());
		}
		return hp;
	}

	@Override
	public String toString() {
		StringBuffer buf = new StringBuffer(40);
		if (isAll(this.host)) {
			buf.append("*");
		} else {
			buf.append(this.host);
		}
		buf.append(":");
		buf.append(getPort());
		return buf.toString();
	}

}
